package com.test.demo;

import com.test.demo.receive.Receive;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;


@SpringBootApplication
public class SpringBootRabbitMqApplication {

    final static String queueName="spring-boot";

    /**
     * 队列
     * @return
     */
    @Bean
    Queue queue(){
        return new Queue(queueName,false);
    }

    /**
     * 交换器
     * @return
     */
    @Bean
    TopicExchange exchange(){
        return new TopicExchange("spring-boot-exchange");
    }

    /**
     * 绑定，通过binding将queue和exchange进行绑定，使exchange能够准确的将消息推送给queue
     * @param queue 队列
     * @param exchange  交换器
     * @return
     */
    @Bean
    Binding binding(Queue queue,TopicExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(queueName);
    }

    /**
     * 注入消息监听容器
     * @param connectionFactory 连接池
     * @param listenerAdapter 监听适配器
     * @return
     */
    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter){
        SimpleMessageListenerContainer container=new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(listenerAdapter);
        return container;
    }

    /**
     * 指定监听者和监听方法
     * @param receive
     * @return
     */
    @Bean
    MessageListenerAdapter adapter(Receive receive){
        return new MessageListenerAdapter(receive,"receiveMessage");
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringBootRabbitMqApplication.class, args);
    }

}
